package com.crm.system.controller.finance.paymentRecordManager;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.DateUtil;
import com.crm.common.util.ExcelUtil4;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.finance.paymentRecordManager.PaymentRecordQO;
import com.crm.model.vo.finance.paymentRecordManager.PaymentRecordExportVO;
import com.crm.model.vo.finance.paymentRecordManager.PaymentRecordVO;
import com.crm.system.service.finance.paymentRecordManager.PaymentRecordService;
import com.crm.system.service.returnMoney.ReturnMoneyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * @ Author ：pym
 * @ Date   ：2021/8/19 9:39
 */
@RestController
@RequestMapping("/paymentRecord")
@Slf4j
public class PaymentRecordController {

    @Autowired
    private PaymentRecordService paymentRecordService;

    @Autowired
    private ReturnMoneyService returnMoneyService;

    /**
     * 财务 到款记录
     * @Author pym
     * @Date  2021/8/19 10:33
     * @param request
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @param paymentRecordQO -查询条件
     * @return {@link {com.crm.common.model.DataResponse}}
     */
    @PostMapping("/selectPaymentRecordList")
    private DataResponse selectPaymentRecordList(HttpServletRequest request,
                                                      @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                                      @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                                      @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                                      @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                                      PaymentRecordQO paymentRecordQO){
        DhPageInfo<PaymentRecordVO> paymentRecordVOList = paymentRecordService.selectPaymentRecordList(pageIndex,pageSize,sortName,sortOrder,paymentRecordQO);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),paymentRecordVOList);
    }

    /**
     * 财务 导出到款记录
     * @Author pym
     * @Date  2021/8/19 15:14
     * @param request
     * @param response
     * @param paymentRecordQO -查询条件
     * @return {@link }
     */
    @GetMapping(value="/exportPaymentRecord")
    public void exportPaymentRecord(HttpServletRequest request, HttpServletResponse response,
                                    PaymentRecordQO paymentRecordQO) throws Exception {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode("到款记录 "+ DateUtil.getDate("yyyy-MM-dd HH:mm:ss"), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = ExcelUtil4.getHorizontalCellStyleStrategy();
            List<PaymentRecordExportVO> paymentRecordExportVOList = paymentRecordService.selectPaymentRecordExportVOList(paymentRecordQO);
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), PaymentRecordExportVO.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("到款记录")
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .doWrite(paymentRecordExportVOList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
            log.error("paymentRecord exportPaymentRecord error:", e);
        }
    }

    /**
     * 根据主键Id修改提成发放状态
     * @Author pym
     * @Date  2021/9/24 10:08
     * @param finishOrderProductIds 回款记录表主键
     * @param royaltyStatus 提成发放状态
     * @return {@link {com.crm.common.model.DataResponse}}
     */
    @PostMapping("/updateRoyaltyStatusByReturnMoneyId")
    private DataResponse updateRoyaltyStatusByReturnMoneyId(@RequestParam(value = "finishOrderProductIds") List<String> finishOrderProductIds,
                                                            @RequestParam(value = "royaltyStatus") String royaltyStatus) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if (Objects.nonNull(userAccount)) {
            returnMoneyService.updateRoyaltyStatusByReturnMoneyId(finishOrderProductIds, royaltyStatus);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

}
